import {
  addCommitUserUsingPOST,
  deleteCommitUserUsingDELETE,
  editCommitUserUsingPUT,
  listCommitUserUsingGET,
} from '@/services/model/commitUserController';
import { useModel } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Form, message, Popconfirm, Space } from 'antd';
import React, { useRef, useState } from 'react';

export type CommitUserColumns = {
  /** 主键id */
  id: number;
  /** 姓名 */
  name?: string;
  /** 角色 */
  role?: string;
  /** 用户名 */
  username?: string;
};
type LeftTableProps = {
  onClickRow: (row: CommitUserColumns) => void;
};
const LeftTable: React.FC<LeftTableProps> = (props: LeftTableProps) => {
  const { initialState } = useModel('@@initialState');
  const actionRef = useRef<ActionType>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly CommitUserColumns[]>([]);
  const [form] = Form.useForm();
  const initListCommitUser = async () => {
    const result = await listCommitUserUsingGET();
    const commitUserList: CommitUserColumns[] | undefined = result.data?.map((item) => {
      return {
        ...item,
        role: item.role + '',
      };
    });
    return {
      data: commitUserList,
      total: 3,
      success: true,
    };
  };
  const onDelete = async (id: number) => {
    const result = await deleteCommitUserUsingDELETE({
      id,
      currentUserId: initialState?.currentUser?.id,
    });
    if (result.code === 0 && result.data) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error(result.message);
    }
  };
  const onSave = async (row: any) => {
    const currentUserId = initialState?.currentUser?.id;
    const newCommitUser: API.AddCommitUserQuery = {
      currentUserId,
      name: row.name,
      role: row.role,
      username: row.username,
    };
    const result = await addCommitUserUsingPOST(newCommitUser);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
    } else {
      message.error(result.message);
    }
    actionRef.current?.reload();
  };
  const onEdit = async (row: any) => {
    const currentUserId = initialState?.currentUser?.id;
    const newCommitUser: API.EditCommitUserQuery = {
      currentUserId,
      id: row.id,
      name: row.name,
      role: row.role,
      username: row.username,
    };
    const result = await editCommitUserUsingPUT(newCommitUser);
    if (result.code === 0 && result.data) {
      message.success('修改成功');
    } else {
      message.error(result.message);
    }
    actionRef.current?.reload();
  };

  const columns: ProColumns<CommitUserColumns>[] = [
    {
      title: 'id',
      key: 'id',
      dataIndex: 'id',
      width: '10%',
      hideInTable: true,
    },
    {
      title: '用户名',
      key: 'username',
      dataIndex: 'username',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '姓名',
      key: 'name',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '角色',
      key: 'role',
      dataIndex: 'role',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '管理员',
          status: 'Error',
        },
        1: {
          text: '计划管理员',
          status: 'Success',
        },
        2: {
          text: '质量管理员',
          status: 'Success',
        },
        3: {
          text: 'QMS',
          status: 'Success',
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            form.resetFields();
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'onDelete'}
          title="你想要删除这个用户吗"
          onConfirm={() => onDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <a key="deletable">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <Space style={{margin: "10px 10px 0px 10px"}}>
        <Button
          type="primary"
          onClick={() => {
            actionRef.current?.addEditRecord?.({
              id: (Math.random() * 1000000).toFixed(0),
              type: 'addCommitUser',
            });
          }}
          icon={<PlusOutlined />}
        >
          新增 人员信息
        </Button>
        <Button
          key="rest"
          onClick={() => {
            form.resetFields();
          }}
        >
          重置表单
        </Button>
      </Space>

      <EditableProTable<CommitUserColumns>
        rowKey="id"
        // scroll={{
        //   x: 600,
        // }}
        onRow={(record) => {
          return {
            onClick: () => {
              props.onClickRow(record);
            },
          };
        }}
        actionRef={actionRef}
        headerTitle="用户表"
        scroll={{y: 'calc(100vh - 205px)'}}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        columns={columns}
        request={() => initListCommitUser()}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          form,
          editableKeys,
          onSave: async (key, row: any) => {
            if (row.type === 'addCommitUser') {
              await onSave(row);
            } else {
              await onEdit(row);
            }
            // 如果是原始数据没有username等属性值，则修改
          },
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
    </>
  );
};

export default LeftTable;
